package ui;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashMap;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

import draft.*;
import draft.Player.*;

public class AvailablePlayerPanel extends JPanel{

	static PlayerPanel ppanel;
	static PlayerList all;
	static PlayerList qb;
	static PlayerList rb;
	static PlayerList wr;
	static PlayerList te;
	static PlayerList k;
	static PlayerList def;
	JTabbedPane pane;

	public AvailablePlayerPanel(PlayerPanel ppanel){
		AvailablePlayerPanel.ppanel = ppanel;
		setLayout(new BorderLayout());
		
		HashMap<Position, ArrayList<Player>> players = new HashMap<Position, ArrayList<Player>>();

		for (Position p : Position.values()) {
			players.put(p, new ArrayList<Player>());
		}
		
		for (Player p : FantasyManager.players) {
			players.get(p.getPosition()).add(p);
		}
		all = new PlayerList(FantasyManager.players);
		qb = new PlayerList(players.get(Position.QB));
		rb = new PlayerList(players.get(Position.RB));
		wr = new PlayerList(players.get(Position.WR));
		te = new PlayerList(players.get(Position.TE));
		def = new PlayerList(players.get(Position.DEF));
		k = new PlayerList(players.get(Position.K));
		pane = new JTabbedPane();
		pane.addTab("ALL", all);
		pane.addTab("QB", qb);
		pane.addTab("RB", rb);
		pane.addTab("WR", wr);
		pane.addTab("TE", te);
		pane.addTab("K", k);
		pane.addTab("DEF", def);
		add (pane, BorderLayout.CENTER);
		JButton button = new JButton("Draft Player");
		button.addActionListener(new DraftListener());
		add(button, BorderLayout.SOUTH);
		setBackground(Color.GRAY);
		setVisible(true);
	}
	
	
	public static void removePlayer (Player p) {
		all.removePlayer(p);
		switch (p.getPosition()) {
		case QB:
			qb.removePlayer(p);
			break;
		case RB:
			rb.removePlayer(p);
			break;
		case WR:
			wr.removePlayer(p);
			break;
		case TE:
			te.removePlayer(p);
			break;
		case K:
			k.removePlayer(p);
			break;
		case DEF:
			def.removePlayer(p);
			break;
		}
		ppanel.update();
	}


	private class DraftListener implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			final Player selected = (Player) ((PlayerList) pane.getSelectedComponent()).getList().getSelectedValue();
			if (selected != null){
				removePlayer(selected);
				
				new Thread(new Runnable () {
					public void run() {
						FantasyManager.receiveTurn(selected);
						FantasyManager.client.advanceTurn();
					}
				}).start();
				
			}
		}

	}
}
